<template>
	<view class="searchLayout">
		<view class="search">
			<uni-search-bar 
				@confirm="onSearch"
				focus 
				placeholder="搜索"
				v-model="queryParams.keyword">
			</uni-search-bar>
		</view>
		<view v-if="historySearch.length">
			<view class="history">
				<view class="topTitle">
					<view class="text">最近搜索</view>
					<view class="icon" @click="removeHistory">
						<uni-icons type="trash" size="25"></uni-icons>
					</view>
				</view>
				<view class="tabs">
					<view class="tab" v-for="tab in historySearch" :key="tab" 
					 @click="clickTab(tab)">{{tab}}</view>		
				</view>
			</view>
		</view>
		<view class="recommend" v-if="recommendList.length">
			<view class="topTitle">
				<view class="text">热门搜索</view>				
			</view>
			<view class="tabs">				
				<view class="tab" v-for="tab in recommendList" :key="tab" 
				 @click="clickTab(tab)">{{tab}}</view>
			</view>
		</view>
	</view>
</template>


<script setup>
import {ref} from "vue";
import {apiSearchData} from "@/api/apis.js";

const queryParams = ref({
	keyword: ""
});

const historySearch = ref(uni.getStorageSync("historySearch") || []);
const recommendList = ref(["科幻", "三体", "刘慈欣", "球形闪电", "流浪地球"]);

const onSearch = async () => {
    if (!queryParams.value.keyword) return;
    try {
        uni.showLoading();
        // 更改参数名从 'keyword' 为 'name' 并确保使用 encodeURIComponent 来避免乱码
        const response = await apiSearchData({name: queryParams.value.keyword});
        uni.setStorageSync("historySearch", [...new Set([queryParams.value.keyword, ...historySearch.value])].slice(0, 10));
        uni.navigateTo({
            url: `/pages/classlist/searchlist?name=${queryParams.value.keyword}`
        });
    } finally {
        uni.hideLoading();
    }
};


const clickTab = (value) => {
	queryParams.value.keyword = value;
	onSearch();
};

const removeHistory = () => {
	uni.showModal({
		title: "是否清空历史搜索？",
		success: res => {
			if (res.confirm) {
				uni.removeStorageSync("historySearch");
				historySearch.value = [];
			}
		}
	});
};

</script>

<style lang="scss" scoped>
.searchLayout{
	.search{
		padding:0 10rpx;
	}
	.topTitle{
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 32rpx;
		color:#999;
	}
	.history{
		padding:30rpx;		
	}
	.recommend{
		padding:30rpx;
	}
	.tabs{
		display: flex;		
		align-items: center;
		flex-wrap: wrap;
		padding-top:20rpx;
		.tab{
			background: #F4F4F4;
			font-size: 28rpx;
			color:#333;
			padding:10rpx 28rpx;
			border-radius: 50rpx;
			margin-right: 20rpx;
			margin-top: 20rpx;
		}
	}	
	.list{
		display: grid;
		grid-template-columns: repeat(3,1fr);
		gap: 5rpx;
		padding:20rpx 5rpx;		
		.item{
			height: 440rpx;
			image{
				width: 100%;
				height: 100%;
				display: block;
			}			
		}		
	}
}
</style>
